<?php 
/**
 * Response Pjq Class
 *
 * @author Richard Thomas <lists@cyberlot.net>
 * @version 0.1
 * @package pjq
 * @subpackage main
 * @copyright Copyright &copy; 2007, Richard Thomas
 */


/**
 * Pjq Response Class
 */

class Ajax_Response {
  /**
   * @access private
   * @var object
   */
  private static $Pjq_Object;

  /**
   * @access private
   * @var array
   */
  private static $responses;

  /**
   * An array of tested jquery methods, Other methods might work
   * But they will log an error
   * @access private
   * @var array
   */
  var $validBaseMethods = Array('addClass','attr');


  /**
   * Access method to ensure we only have a single instance at any one time
   * 
   * @return object
   */
  public static function getInstance() {
    if(!self::$Pjq_Object) {
      self::$Pjq_Object = new Ajax_Response();
    }
    return self::$Pjq_Object;
  }

  /**
   * Handle callbacks, methods have to use getInstance to get access
   * to reponse features
   * 
   * @param mixed
   */
  function processCallback($callback, $params) {
    if(is_array($callback))
    {
    	$obj=$callback[1];
    	$method=$callback[0];
    	$obj->$method($params);
    }
    else 
    {
  		call_user_func_array($callback, $params);
    }
  } 
  /**
   * 
   * @param json
   */
  function getResponse() {
    return json_encode(self::$responses);
  }

  /**
   * Magic class that handles the basic magic by building the array
   * that ends up json encoded 
   *
   * @param string
   * @param array
   */
  function __call($method, $args) {
    if(!in_array($method, $this->validBaseMethods)) {
      error_log($method.' method has not been tested with jquery to work!');
    }
    if(sizeof(@$args == 1) AND !is_array(@$args[0])) {
      $args = @$args[0];
    } 
    $rep = array();
    $rep['m'] = $method;
    if($args) {
      $rep['a'] = $args;
    }
    self::$responses[] = $rep;
  }
}